package org.smart4j.chapter2.util;

import com.mysql.jdbc.StringUtils;

/**
 * 转型操作工具类
 */
public final class CastUtil {
    public static String castString(Object obj) {
        return CastUtil.castString(obj, "");
    }

    public static String castString(Object obj, String defaultValue) {
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    public static double castDouble(Object obj) {
        return CastUtil.castDouble(obj, 0);
    }

    public  static  double castDouble(Object object,double defaultValue){
        double doubleValue=defaultValue;
        if (object!=null){
            String strValue=castString(object);
            if (StringUtil.isNotEmpty(strValue)){
                try {
                    doubleValue=Double.parseDouble(strValue);
                }catch (NumberFormatException e){
                    doubleValue =defaultValue;
                }
            }
        }
        return doubleValue;
    }

    public  static  long castLong(Object object){
        return CastUtil.castLong(object,0);
    }

    public  static  long castLong(Object object,long defaultValue){
        long longValue=defaultValue;
        if (object!=null){
            String strValue=castString(object);
            if (StringUtil.isNotEmpty(strValue)){
                try {
                    longValue=Long.parseLong(strValue);
                }catch (NumberFormatException e){
                    longValue =defaultValue;
                }
            }
        }
        return longValue;
    }

    public  static  int castInt(Object object){
        return CastUtil.castInt(object,0);
    }

    public  static  int castInt(Object object,int defaultValue){
        int intValue=defaultValue;
        if (object!=null){
            String strValue=castString(object);
            if (StringUtil.isNotEmpty(strValue)){
                try {
                    intValue=Integer.parseInt(strValue);
                }catch (NumberFormatException e){
                    intValue =defaultValue;
                }
            }
        }
        return intValue;
    }

    public  static  boolean castBoolean(Object object){
        return CastUtil.castBoolean(object,false);
    }

    public  static  boolean castBoolean(Object object,boolean defaultValue){
        boolean booleanValue=defaultValue;
        if (object!=null){
            booleanValue=Boolean.parseBoolean(castString(object));
        }
        return booleanValue;
    }

}
